package com.cool.reggie.modules.employee.controller;

import com.cool.reggie.utils.ResultData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.UUID;

/**
 * 常见控制器
 *
 * @Author ifredomvip@gmail.com
 * @Date 2022/7/7 10:41
 * @Version 1.0.0
 * @Description
 **/
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${file.upload.dir}")
    private String uploadPath;

    @Value("${file.download.dir}")
    private String downloadPath;

    @PostMapping("upload")
    public ResultData upload(MultipartFile file) {
        log.info(file.toString());

        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        String filename = UUID.randomUUID().toString();

        File uploadFile = new File(uploadPath);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }

        try {
            file.transferTo(new File(uploadPath + filename + suffix));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return ResultData.ok(filename + suffix);
    }

    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) throws IOException {


        File file = new File(downloadPath + name);
        FileInputStream fileInputStream = new FileInputStream(file);

        ServletOutputStream outputStream = response.getOutputStream();

        response.setContentType(MediaType.IMAGE_JPEG_VALUE);
        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(name, "UTF-8"));

        byte[] bytes = new byte[1024];
        int len = fileInputStream.read(bytes);


        try {
            while (len != -1) {
                outputStream.write(bytes, 0, len);
                len = fileInputStream.read(bytes);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
                outputStream.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

}
